package com.innovation.ic.cyz.base.service.cyz.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.cyz.base.mapper.cyz.*;
import com.innovation.ic.cyz.base.model.cyz.*;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.pojo.constant.AvdRelModule;
import com.innovation.ic.cyz.base.pojo.constant.AvdUserCenterOption;
import com.innovation.ic.cyz.base.pojo.variable.cyz.users_center.UserCenterListPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.users_center.UserCenterPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.users_center.UserSumPojo;
import com.innovation.ic.cyz.base.service.cyz.UsersCenterService;
import com.innovation.ic.cyz.base.vo.cyz.UserCenterVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional
public class UsersCenterServiceImpl extends ServiceImpl<UserMapper, User> implements UsersCenterService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private AvdMapper avdMapper;
    @Resource
    private AvdRelMapper avdRelMapper;
    @Resource
    private AvdTypeMapper avdTypeMapper;
    @Resource
    private AvdTagMapper avdTagMapper;
    @Resource
    private UserViewLogMapper userViewLogMapper;

    /**
     * 用户中心列表信息
     *
     * @param userCenterVo
     * @return
     */
    public ServiceResult<UserCenterListPojo> allUsersCenter(UserCenterVo userCenterVo) {
        ServiceResult<UserCenterListPojo> listServiceResult = new ServiceResult<>();
        Integer pageSize = userCenterVo.getPageSize();
        Integer pageNo = (userCenterVo.getPageNo() - 1) * pageSize;
        if (!StringUtils.validateParameter(userCenterVo.getUserId())) {//进入用户中心页面
            if (userCenterVo.getSource() != null) {//有来源条件返回数据
                List<User> userList = userMapper.allUsersCenterFindSource(pageNo, pageSize, userCenterVo.getSource());//获取出基本用户信息(来源)
                List list = usersCenterList(userList);
                UserCenterListPojo userCenterListPojo = new UserCenterListPojo();
                userCenterListPojo.setUserCenterPojo(list);
                userCenterListPojo.setNum(list.size());
                listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
                listServiceResult.setSuccess(Boolean.TRUE);
                listServiceResult.setResult(userCenterListPojo);
                return listServiceResult;
            }
            //没有来源的普通用户中心数据展示
            List<User> userList = userMapper.allUsersCenter(pageNo, pageSize);//获取出基本用户信息
            List list = usersCenterList(userList);
            UserCenterListPojo userCenterListPojo = new UserCenterListPojo();
            userCenterListPojo.setUserCenterPojo(list);
            userCenterListPojo.setNum(list.size());
            listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            listServiceResult.setSuccess(Boolean.TRUE);
            listServiceResult.setResult(userCenterListPojo);
            return listServiceResult;
        } else {//进入投稿，点赞，收藏，浏览页面
            //获取到当前用户数据
            User user = userMapper.selectById(userCenterVo.getUserId());
            if (AvdUserCenterOption.MyWrite == userCenterVo.getOperation()) {//进入用户中心投稿数量页面
                //去通过创建id查询相关数据并分页
                if (userCenterVo.getNameId() == null || userCenterVo.getNameId() == 0) {//如果当前条件查询不带所属类别
                    List<Avd> avdList = avdMapper.selectListAvd(pageNo, pageSize, user.getId(), userCenterVo.getModule(), userCenterVo.getCreateDate());
                    List list = usersContriButionList(user, avdList);
                    //进行降序展示
                    list.sort(Comparator.comparing(UserCenterPojo::getCreateDate).reversed());
                    UserCenterListPojo userCenterListPojo = new UserCenterListPojo();
                    userCenterListPojo.setUserCenterPojo(list);
                    userCenterListPojo.setNum(list.size());
                    listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
                    listServiceResult.setSuccess(Boolean.TRUE);
                    listServiceResult.setResult(userCenterListPojo);
                    return listServiceResult;
                }
                List<Avd> avdList = avdMapper.selectListAvd(pageNo, pageSize, user.getId(), userCenterVo.getModule(), userCenterVo.getCreateDate());//获取避坑指南数据
                QueryWrapper<AvdRel> avdRelQueryWrapper = new QueryWrapper<>();
                avdRelQueryWrapper.eq("avd_rel_id", userCenterVo.getNameId());
                List<AvdRel> avdRels = avdRelMapper.selectList(avdRelQueryWrapper);//获取所属类别数据
                List list = usersContriButionClassificationList(user, avdRels, avdList);
                //进行降序展示
                list.sort(Comparator.comparing(UserCenterPojo::getCreateDate).reversed());
                UserCenterListPojo userCenterListPojo = new UserCenterListPojo();
                userCenterListPojo.setUserCenterPojo(list);
                userCenterListPojo.setNum(list.size());
                listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
                listServiceResult.setSuccess(Boolean.TRUE);
                listServiceResult.setResult(userCenterListPojo);
                return listServiceResult;
            } else if (AvdUserCenterOption.MyLike == userCenterVo.getOperation()) {//进入点赞页面
                //获取到用户记录点赞相关数据并且分页
                List<UserViewLog> userViewLogs = userViewLogMapper.selectPageUser(pageNo, pageSize, userCenterVo.getUserId(), AvdUserCenterOption.MyLike);
                List list = usersFabulous(user, userViewLogs, userCenterVo);
                //进行降序展示
                list.sort(Comparator.comparing(UserCenterPojo::getCreateDate).reversed());
                UserCenterListPojo userCenterListPojo = new UserCenterListPojo();
                userCenterListPojo.setUserCenterPojo(list);
                userCenterListPojo.setNum(list.size());
                listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
                listServiceResult.setSuccess(Boolean.TRUE);
                listServiceResult.setResult(userCenterListPojo);
                return listServiceResult;
            } else if (AvdUserCenterOption.MyCollect == userCenterVo.getOperation()) {//进入收藏页面
                //获取到用户记录收藏相关数据并且分页
                List<UserViewLog> userViewLogs = userViewLogMapper.selectPageUser(pageNo, pageSize, userCenterVo.getUserId(), AvdUserCenterOption.MyCollect);
                List list = usersFabulous(user, userViewLogs, userCenterVo);
                //进行降序展示
                list.sort(Comparator.comparing(UserCenterPojo::getCreateDate).reversed());
                UserCenterListPojo userCenterListPojo = new UserCenterListPojo();
                userCenterListPojo.setUserCenterPojo(list);
                userCenterListPojo.setNum(list.size());
                listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
                listServiceResult.setSuccess(Boolean.TRUE);
                listServiceResult.setResult(userCenterListPojo);
                return listServiceResult;
            }
            //进入浏览页面
            //获取到用户记录浏览相关数据并且分页
            List<UserViewLog> userViewLogs = userViewLogMapper.selectPageUser(pageNo, pageSize, userCenterVo.getUserId(), AvdUserCenterOption.MyView);
            List list = usersFabulous(user, userViewLogs, userCenterVo);
            //进行降序展示
            list.sort(Comparator.comparing(UserCenterPojo::getCreateDate).reversed());
            UserCenterListPojo userCenterListPojo = new UserCenterListPojo();
            userCenterListPojo.setUserCenterPojo(list);
            userCenterListPojo.setNum(list.size());
            listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            listServiceResult.setSuccess(Boolean.TRUE);
            listServiceResult.setResult(userCenterListPojo);
            return listServiceResult;
        }
    }

    private List usersFabulous(User user, List<UserViewLog> userViewLogs, UserCenterVo userCenterVo) {//用户中心点赞页面
        ArrayList<UserCenterPojo> list = new ArrayList<>();
        for (UserViewLog userViewLog : userViewLogs) {
            UserCenterPojo userCenterPojo = new UserCenterPojo();
            Long businessId = userViewLog.getBusinessId();//用户记录中的避坑指南中的文章id
            Avd avd = avdMapper.findAvdData(businessId, userCenterVo.getCreateDate(), userCenterVo.getModule());//获取避坑指南中的文章信息根据发布时间
            if (avd == null) {
                continue;
            }
            AvdRel avdRelData = avdRelMapper.selectAvdRelData(avd.getId(), AvdRelModule.Type, userCenterVo.getNameId());//获取关联所属类型信息根据（文章id/关系/分类）
            if (avdRelData == null) {
                continue;
            }
            QueryWrapper<AvdRel> avdTagQueryWrapper = new QueryWrapper<>();
            avdTagQueryWrapper.eq("avd_id", avd.getId());
            avdTagQueryWrapper.eq("module", AvdRelModule.Tag);
            AvdRel avdTagData = avdRelMapper.selectOne(avdTagQueryWrapper);//获取关联标签数据
            Long avdTagId = avdTagData.getAvdRelId();//标签id
            AvdTag avdTag1 = avdTagMapper.selectById(avdTagId);//获取标签数据
            Long avdRelId = avdRelData.getAvdRelId();//分类id
            AvdType avdType = avdTypeMapper.selectById(avdRelId);//获取所属类型数据
            userCenterPojo.setId(avd.getId());//文章id
            userCenterPojo.setUserId(user.getId());//用户id
            userCenterPojo.setUserName(user.getUsername());//姓名
            userCenterPojo.setModule(avd.getModule());//类型
            userCenterPojo.setCover(avd.getCover());//封面
            userCenterPojo.setTitle(avd.getTitle());//标题
            userCenterPojo.setName(avdType.getName());//所属类型名
            userCenterPojo.setDescription(avd.getDescription());//描述
            userCenterPojo.setTag(avdTag1.getTag());//标签
            userCenterPojo.setCreateDate(avd.getCreateDate());//创建时间
            userCenterPojo.setStatus(avd.getApproveStatus());//状态
            userCenterPojo.setParagraph(avd.getParagraph());//正文
            list.add(userCenterPojo);
        }
        return list;
    }

    private List usersContriButionClassificationList(User user, List<AvdRel> avdRels, List<Avd> avdList) {//用户中心投稿页面条件查询
        ArrayList<UserCenterPojo> list = new ArrayList<>();
        for (AvdRel avdRel : avdRels) {
            Long avdId = avdRel.getAvdId();//所属类别中的避坑指南信息
            for (Avd avd : avdList) {
                if (avdId.equals(avd.getId())) {//对比所属分类中数据一定得是当前用户的数据
                    UserCenterPojo userCenterPojo = new UserCenterPojo();
                    QueryWrapper<AvdRel> avdRelQueryWrapper = new QueryWrapper<>();
                    avdRelQueryWrapper.eq("avd_id", avdId);
                    avdRelQueryWrapper.eq("module", AvdRelModule.Type);
                    AvdRel avdRelData = avdRelMapper.selectOne(avdRelQueryWrapper);//获取关联所属类型信息
                    QueryWrapper<AvdRel> avdTagQueryWrapper = new QueryWrapper<>();
                    avdTagQueryWrapper.eq("avd_id", avdId);
                    avdTagQueryWrapper.eq("module", AvdRelModule.Tag);
                    AvdRel avdTagData = avdRelMapper.selectOne(avdTagQueryWrapper);//获取关联标签数据
                    Long avdTagId = avdTagData.getAvdRelId();//标签id
                    AvdTag avdTag1 = avdTagMapper.selectById(avdTagId);//获取标签数据
                    Long avdRelId = avdRelData.getAvdRelId();//分类id
                    AvdType avdType = avdTypeMapper.selectById(avdRelId);//获取所属类型数据
                    userCenterPojo.setId(avd.getId());//文章id
                    userCenterPojo.setUserId(user.getId());//用户id
                    userCenterPojo.setUserName(user.getUsername());//姓名
                    userCenterPojo.setModule(avd.getModule());//类型
                    userCenterPojo.setCover(avd.getCover());//封面
                    userCenterPojo.setTitle(avd.getTitle());//标题
                    userCenterPojo.setName(avdType.getName());//所属类型名
                    userCenterPojo.setDescription(avd.getDescription());//描述
                    userCenterPojo.setTag(avdTag1.getTag());//标签
                    userCenterPojo.setCreateDate(avd.getCreateDate());//创建时间
                    userCenterPojo.setStatus(avd.getApproveStatus());//状态
                    userCenterPojo.setParagraph(avd.getParagraph());//正文
                    list.add(userCenterPojo);
                }
            }
        }
        return list;
    }

    private List usersContriButionList(User user, List<Avd> avdList) {//用户中心投稿页面
        ArrayList<UserCenterPojo> list = new ArrayList<>();
        for (Avd avd : avdList) {
            UserCenterPojo userCenterPojo = new UserCenterPojo();
            Long id = avd.getId();//获取出文章id 用于获取 所属类别
            QueryWrapper<AvdRel> avdRelQueryWrapper = new QueryWrapper<>();
            avdRelQueryWrapper.eq("avd_id", id);
            avdRelQueryWrapper.eq("module", AvdRelModule.Type);
            AvdRel avdRel = avdRelMapper.selectOne(avdRelQueryWrapper);//获取关联所属类型信息
            QueryWrapper<AvdRel> avdTagQueryWrapper = new QueryWrapper<>();
            avdTagQueryWrapper.eq("avd_id", id);
            avdTagQueryWrapper.eq("module", AvdRelModule.Tag);
            AvdRel avdTag = avdRelMapper.selectOne(avdTagQueryWrapper);//获取关联标签数据
            Long avdTagId = avdTag.getAvdRelId();//标签id
            AvdTag avdTag1 = avdTagMapper.selectById(avdTagId);//获取标签数据
            Long avdRelId = avdRel.getAvdRelId();//分类id
            AvdType avdType = avdTypeMapper.selectById(avdRelId);//获取所属类型数据
            userCenterPojo.setId(avd.getId());//文章id
            userCenterPojo.setUserId(user.getId());//用户id
            userCenterPojo.setUserName(user.getUsername());//姓名
            userCenterPojo.setModule(avd.getModule());//类型
            userCenterPojo.setCover(avd.getCover());//封面
            userCenterPojo.setTitle(avd.getTitle());//标题
            userCenterPojo.setName(avdType.getName());//所属类型名
            userCenterPojo.setDescription(avd.getDescription());//描述
            userCenterPojo.setTag(avdTag1.getTag());//标签
            userCenterPojo.setCreateDate(avd.getCreateDate());//创建时间
            userCenterPojo.setStatus(avd.getApproveStatus());//状态
            userCenterPojo.setParagraph(avd.getParagraph());//正文
            list.add(userCenterPojo);
        }
        return list;
    }

    private List usersCenterList(List<User> userList) {//用户中心页面方法
        ArrayList<UserCenterPojo> list = new ArrayList<>();
        for (User user : userList) {
            UserCenterPojo userCenterPojo = new UserCenterPojo();
            String id = user.getId();//获取到用户主键用于去避坑指南中查询对应数据
            userCenterPojo.setUserId(id);//用户主键
            userCenterPojo.setUserName(user.getUsername());//用户名
            userCenterPojo.setSource(user.getSource());//用户来源
            userCenterPojo.setAvatar(user.getAvatar());//头像
            userCenterPojo.setResume(user.getResume());//个人简介
            QueryWrapper<Avd> avdQueryWrapper = new QueryWrapper<>();
            avdQueryWrapper.eq("creator_id", id);
            Integer contribution = avdMapper.selectCount(avdQueryWrapper);//获取当前用户到投稿数量
            userCenterPojo.setContributionNum(contribution);//投稿数量
            UserSumPojo userSumPojo = avdMapper.allSum(id);//拿到当前用户在避坑指南中(阅读数量、收藏数量、点赞数量)总和
            if (userSumPojo == null) {
                userCenterPojo.setBrowseNum(0);//浏览数量
                userCenterPojo.setThumbsUpNum(0);//点赞数量
                userCenterPojo.setCollectionNum(0);//收藏数量
                list.add(userCenterPojo);
            } else {
                userCenterPojo.setBrowseNum(userSumPojo.getViewSum());//浏览数量
                userCenterPojo.setThumbsUpNum(userSumPojo.getLikeSum());//点赞数量
                userCenterPojo.setCollectionNum(userSumPojo.getCollectSum());//收藏数量
                list.add(userCenterPojo);
            }
        }
        return list;
    }

    /**
     * 用户中心中下拉框(所属类别)
     *
     * @return
     */
    public ServiceResult<List<AvdType>> allType() {
        ServiceResult<List<AvdType>> serviceResult = new ServiceResult<>();
        List<AvdType> avdTypeList = avdTypeMapper.selectList(null);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(avdTypeList);
        return serviceResult;
    }

    /**
     * 用户中心投稿信息(删除)
     *
     * @param userCenterVo
     * @return
     */
    public void deleteContribution(UserCenterVo userCenterVo) {
        UpdateWrapper<Avd> avdUpdateWrapper = new UpdateWrapper<>();
        avdUpdateWrapper.eq("id", userCenterVo.getId());
        Avd avd = new Avd();
        avd.setStatus(AvdUserCenterOption.Delete);
        avdMapper.update(avd, avdUpdateWrapper);
    }

    /**
     * 用户中心投稿信息(审核)
     *
     * @param userCenterVo
     * @return
     */
    public void updateApproveStatus(UserCenterVo userCenterVo) {
        UpdateWrapper<Avd> avdUpdateWrapper = new UpdateWrapper<>();
        avdUpdateWrapper.eq("id", userCenterVo.getId());
        Avd avd = new Avd();
        avd.setApproveStatus(userCenterVo.getApproveStatus());
        avdMapper.update(avd, avdUpdateWrapper);
    }
}
